//
//  ST_ShowTraitCell.swift
//  btvideo
//
//  Created by mac on 2020/3/19.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SwiftyJSON
import NIMSDK
import SwiftyUserDefaults


class ST_ShowTraitCell: UICollectionViewCell {
    
    static let two_line_max_height = 35.cgFloat
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.backgroundColor = Color.white
        self.contentView.clipsToBounds = true
//        self.contentView.backgroundColor = Color.random
        
        contentView.addSubview(cover_image_view)
        
        contentView.addSubview(icon_image_view)
        contentView.addSubview(content_label)
        
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.right.left.equalToSuperview()
            make.height.equalTo(50)
        }
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(5)
            make.left.equalTo(cover_image_view).offset(5)
            make.right.equalToSuperview()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    fileprivate lazy var pauseSignImageView:UIImageView = {
//        let control = UIImageView.init(image: ST_ImageUtils.imageName("pause"))
//        control.isHidden = true
//        return control
//    }()
    
    
    fileprivate lazy var cover_image_view:ST_PairsCenterPeculiarityImageView = {
        let control = ST_PairsCenterPeculiarityImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 20
        return control
    }()
    
    fileprivate lazy var icon_image_view:ST_TriangleView = {
        let control = ST_TriangleView()
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.numberOfLines = 0
        control.isHidden = true
        return control
    }()
  
    var max_content_number_of_lines = 0{
        didSet{
            content_label.numberOfLines = max_content_number_of_lines
        }
    }
    
//    MARK: - Bind Model
    var model = ST_ShowTraitCellModel(){
        didSet{
            
            if let attr = model.content_attr{
                content_label.attributedText = attr
                content_label.isHidden = false
            }else{
                content_label.isHidden = true
            }
            
            cover_image_view.pin_setImage(from: model.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            cover_image_view.snp.updateConstraints { (make) in
                make.height.equalTo(model.firstImageSize.height)
            }
            
            cover_image_view.isCheck = model.state == 1
            
        }
    }
}



extension ST_ShowTraitCell:ST_PecGroupshareViewRectProtocol {
    
    func picutreframe_in_content_view() -> CGRect {
        return self.cover_image_view.frame
    }
    
}

//MARK: - 可以关注的 特质Cell
class ST_TraitOfOperatCell: ST_ShowTraitCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.addSubview(thumbUpBtn)
        contentView.addSubview(more_button)
        
        thumbUpBtn.snp.makeConstraints { (make) in
            make.height.equalTo(33)
            make.left.equalTo(content_label)
//            make.right.equalTo(more_button.snp.left)
//            make.top.equalTo(content_label.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
        
        contentView.addSubview(comment_btn)
        comment_btn.snp.makeConstraints { (make) in
            make.height.equalTo(33)
            make.left.equalTo(thumbUpBtn.snp.right).offset(15)
//            make.top.equalTo(content_label.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
        let moreButtonW = 17.cgFloat
        
        
        more_button.snp.makeConstraints { (make) in
            make.centerY.equalTo(thumbUpBtn)
            make.right.equalToSuperview().offset(-5+(44-moreButtonW)/2.0)
            make.width.height.equalTo(44)
        }
    }
    
    fileprivate lazy var thumbUpBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("home_thumbUp_normal"), for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("home_thumbUp_selected"), for: UIControl.State.selected)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
//        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        control.addTarget(self, action: #selector(thumb_up_click_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    lazy var comment_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImage(ST_ImageUtils.imageName("particularity_comment_cell_icon"), for: UIControl.State.normal)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
//        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        control.isUserInteractionEnabled = false
        return control
    }()
    
    
    fileprivate lazy var more_button:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_更多操作")!)
        control.add_touch_up(insideTarget: self, action: #selector(more_btn_click_handle))
//        control.backgroundColor = Color.random
        return control
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var refresh_water_fall_closure:(()->())?
    
    override var model: ST_ShowTraitCellModel{
        didSet{
            
            let str = " " + self.model.thumbUpCount.st_number_description()
            
            self.thumbUpBtn.setTitleForAllStates(str)
            
            self.thumbUpBtn.isSelected = self.model.isThumbUp
            
            self.comment_btn.setTitleForAllStates(" " + self.model.commentCount.st_number_description())
//            print("识别问题：",model,"是否点赞：",model.isThumbUp)
            
        }
    }
    
    @objc func more_btn_click_handle(){
        
        let vc = ST_BTSheetActionController.init(title: nil, message: nil)
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        
        if model.accid == Defaults[.currentUserID]{
            
            let str = NSMutableAttributedString.init(string: "删除")
            
            str.addAttributes(attr, range: NSRange(location: 0, length: str.length))
            
            vc.addAction(ST_BTAlertAction.init(title: str, handler: {[weak self] (action) in
               
                self?.delete_current_group_handle()
                
            }))
            
            vc.show()
            
            return
        }
        
        if ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male || Defaults[.isPanda] {
        
        let str2 = NSMutableAttributedString.init(string: "拉黑")
        
        str2.addAttributes(attr, range: NSRange(location: 0, length: str2.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str2, handler: {[weak self] (action) in
           
            self?.ban_current_user_handle()
            
        }))
        }
        
        let str3 = NSMutableAttributedString.init(string: "举报")
        
        str3.addAttributes(attr, range: NSRange(location: 0, length: str3.length))
        
        vc.addAction(ST_BTAlertAction.init(title: str3, handler: { (action) in
           
            let vc = ST_ReportPersonController()
            vc.userId = self.model.accid
            let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
            GlobalPresent(toController: nav)
            
        }))
        
        vc.show()
        
    }
    
    
    @objc fileprivate func thumb_up_click_handle(){
        
        
        Thumbup(targetAccid: model.accid, groupId: model.group_id.string, peculiarity_id: model.feature_id.string, thumbUpAction: !model.isThumbUp, fromVC: self.parentViewController) { (err) in
            
            self.thumbUpBtn.isSelected = !self.thumbUpBtn.isSelected
            self.model.isThumbUp = !self.model.isThumbUp
            
            let offSet = self.model.isThumbUp ? 1 : -1
            
            self.model.thumbUpCount += offSet
            
            let str = self.model.thumbUpCount.st_number_description()
            
            self.thumbUpBtn.setTitleForAllStates(str)
            
            
        } completion: {
        
            print("点赞成功新Api Service")
            
        }
        
    }
    
    
    @objc func ban_current_user_handle(){
        
        
        BAN_SOMEBODY_HANDLE(userId: model.accid, close_view: false, hud_controller: self.parentViewController)
        
    }
    
    fileprivate func delete_current_group_handle()  {
        
        JVrequest(PH.delGroupContentApi,parameters:  ["feature_id":model.feature_id,"group_id":model.group_id] ,success: { (json) in
            
            NotificationCenter.default.post(name: Notification.Name.my_pairs_user_info_updated, object: nil)
           
            self.refresh_water_fall_closure?()
            
            
        }) { (code, err) in
            
            self.parentViewController?.toast(text: err)
        }
    }
    
}


//MARK: - Model
class ST_ShowTraitCellModel: NSObject {

    enum cellType:Int {
        case image = 0,video
    }
    
    var feature_id = 0

    var featureContentId = 0
    
    var group_id = 0
    
    var accid = ""
    
    var type = cellType.image
    
    var videoUrl = ""
    
    var imageUrl = ""
    
    var width:CGFloat = 0
    
    var height:CGFloat = 0
    
    var duration = 0
    
    

    /** 等于 1  审核中  【新增】
     */
    var state = 0
    
    lazy var displayHeight:CGFloat = {
        
        let w = self.width < 1 ? 1 : self.width
        
        let h = ScreenWidth/w*height
        
//        if h > PairsShareHeaderMaxHeight{
//            return PairsShareHeaderMaxHeight
//        }
        return h
    }()
    
    var sign = ""
    
    
    var nickname = ""
    
    var thumbUpCount = 0
    
    var commentCount = 0
    
    var isAttention = false
    
    var isThumbUp = false
    
    var avatar = ""
    
    
    var featureName = ""
    
    /**
     1 男 2 女
     */
    var peculiarityType = 1
    /*1文字 2 表情*/
    var commentType = 1
//   MARK: - UI properties
    let contentWidth = ((ScreenWidth - 2 * 10 - 15)/2.0).int.cgFloat - 5
    
    var content_attr:NSAttributedString?
    
    var firstImageSize = CGSize.zero
    
    var size = CGSize.zero
    
    override init() {
        super.init()
    }
    
    /**
     从后台的数据结构解析为本身数据结构
     */
    init(json:JSON) {
        
        super.init()
        
        feature_id = json["feature_id"].intValue
        
        featureContentId = json["feature_content_id"].intValue
        
        
        group_id = json["group_id"].intValue
        
        accid = json["accid"].stringValue
        
        videoUrl = json["video_url"].stringValue
        
        imageUrl = json["content"].stringValue
        
        //        类型(1:视频,2:图片)
        if videoUrl != "",videoUrl.count > 3{
            type = .video
        }
        
        sign = json["remark"].stringValue
        
//        sign = "生活在乡村田野的可爱飨灵。喜欢音乐与歌唱，但没有听众。"
        
        width = json["width"].floatValue.cgFloat
        
        height = json["height"].floatValue.cgFloat
        
        
        nickname = json["nickname"].stringValue
        
        avatar = json["avatar"].stringValue
        
        thumbUpCount = json["thumb_up_count"].intValue
        
        commentCount = json["comment_count"].intValue
        
        isAttention = json["is_attention"].boolValue
        
        isThumbUp = json["is_thumb_up"].boolValue
        
        commentType = json["is_emoji_feature"].boolValue ? 2 : 1
        
        featureName = json["feature_name"].stringValue
        
        peculiarityType = json["feature_type"].intValue
//        print("七个00000----01")
        
        self.duration = json["video_full_duration"].intValue
        
        
        create_view_model_set()
    }
    
    
    
    /**
     从后台的数据结构解析为本身数据结构
     */
    init(personModel:ST_PeculiaritySquarePersonChildModel) {
        
        super.init()
        
        feature_id = personModel.feature_id
        
        group_id = personModel.group_id
        
        accid = personModel.accid
        
        videoUrl = personModel.video_url
        
        imageUrl = personModel.content
        
        //        类型(1:视频,2:图片)
        if videoUrl != "",videoUrl.count > 3{
            type = .video
        }
        
        sign = personModel.remark
        
        width = personModel.width.cgFloat
        
        height = personModel.height.cgFloat
        
        create_view_model_set()
    }
    
    static func describe(json_array:[JSON])->[ST_ShowTraitCellModel]{
        
        let array = json_array.map { (json) -> ST_ShowTraitCellModel in
            return ST_ShowTraitCellModel.init(json: json)
        }
        
        return array
    }
    
    static func describe(modelArray:[ST_PeculiaritySquarePersonChildModel])->[ST_ShowTraitCellModel]{
        
        let array = modelArray.map { (json) -> ST_ShowTraitCellModel in
            return ST_ShowTraitCellModel.init(personModel: json)
        }
        
        return array
    }
    
    func create_view_model_set(maxContentHeight:CGFloat = -1){
        
        var content_height = 0.cgFloat
        
        if sign.count > 0{
            
            let attrString = NSMutableAttributedString(string: sign)
            
            let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium),.foregroundColor: UIColor.init(hexString: "#333333")!]
            
            attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
            
            content_attr = attrString
            
            content_height = attrString.height(withConstrainedWidth: contentWidth)
            
//            print("计算的宽度:",contentWidth,"--计算的结果:",content_height)
            
            if maxContentHeight > 0,content_height > maxContentHeight{
                content_height = maxContentHeight
            }
            
            content_height += 5
        }
        
        
//            print("22222----222-----",ST_PinterestHomeCellImageWidth)
            let w = self.width < 1 ? 1 : self.width
            let h = ST_PinterestHomeCellImageWidth/w*self.height
            
            firstImageSize = CGSize.init(width: ST_PinterestHomeCellImageWidth.int.cgFloat, height: h.int.cgFloat)
        
//        print("22222----222-----size:",firstImageSize)
        
        self.size = CGSize.init(width: ST_PinterestHomeCellImageWidth, height: content_height + self.firstImageSize.height)
        
//        print("Bug 00088888:",size)
        
    }
    
}


//MARK: - 需要关注按钮使用
class ST_TraitOfOperatCellModel: ST_ShowTraitCellModel {
    
    override func create_view_model_set(maxContentHeight: CGFloat = -1) {
        super.create_view_model_set(maxContentHeight: maxContentHeight)
        
        
        var offSet = 30.cgFloat
        
        if sign.count < 1{
            offSet += 5
        }
        
        self.size = CGSize.init(width: self.size.width, height: self.size.height + offSet)
        
//        print("七个00000----02")
        
    }
    
    
    
}




func Thumbup(targetAccid:String,groupId:String,peculiarity_id:String,thumbUpAction:Bool,fromVC:UIViewController?,preview:@escaping ((_ err:Bool)->()) , completion:@escaping (()->()) ) {
    
    
    PlayFeedBack()
    
    if targetAccid == ST_BTUserInfoManager.shared.current_account_info?.accid{
        
        let thumbUpHud = ST_BTHUDController.init(noticeText: "不能给自己点赞哦")
        
        GlobalPresent(toController: thumbUpHud, animated: false)
        
        main_thread_execute(afterDelay: 2.5) {
            thumbUpHud.dismiss(animated: false, completion: nil)
        }
        
        return
    }
    
    if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: fromVC) {
        return
    }
    
    preview(false)
    
    let api = !thumbUpAction ? PH.un_thumbUpPeculiarityApi : PH.thumbUpPeculiarityApi
 
    ST_BTGlobalDataCenter.shared.thumbUpPeculiarityEvent(peculiarity_id: groupId, liked_user_id: targetAccid )
    
    JVrequest(api,parameters: ["target_accid":targetAccid,"feature_id":peculiarity_id,"group_id":groupId], success: { (json) in
        
        completion()
        
        NotificationCenter.default.post(name: Notification.Name.thumbUp, object: nil, userInfo: ["fromController":fromVC ?? 0,"isThumbUp":thumbUpAction,"id":groupId])
        
    }) { (code, err) in
        
        preview(true)
        
        fromVC?.toast(text: err)
    }
    
}
